<?php

  /**
  * 获取一个设备的控制类型统计
  * @param mixed $device_id
  */
  function getDeviceControl($device_id){
      //
      $cpn_where['d.id'] = $device_id;
      $cpn = M('project_device')->alias("d")
      ->join(C('DB_PREFIX').'project p ON d.project_id = p.id')
      ->join(C('DB_PREFIX').'tpl_module_template tt ON tt.module_id = p.module_ids and d.cpn_type = tt.cpn_type and d.group_code = tt.group_code')
      ->where($cpn_where)
      ->getField("cpn");
      
      $where['project_device_id'] = $device_id;
      //获取参数
      $param_list =  M('project_design')->alias("pd")
      ->join(C('DB_PREFIX').'device_class_param cp ON pd.param_id = cp.id')
      ->join(C('DB_PREFIX').'device_control dc ON dc.control_code = cp.control_type')
      ->where($where)
      ->group("cp.control_type,cp.control_type_group")
      ->field("dc.control_name,cp.control_type_group")
      ->order("dc.sorts")
      ->select(); 
      $array_names = array_column($param_list,'control_name');
      $array_value = array_count_values($array_names);
      $temp = array($cpn=>1);
      $array_value = array_merge($temp,$array_value);
      $data['sum'] =  $array_value;
      $str = "";
      $count = 0;
      $key_list = array();
      $array_names = array_merge(array($cpn),$array_names);
      foreach($array_names as $k =>$v){
          $str = $str.$v."#";
          $key_list[] = $v;
      }
      $data['str'] =  $str;
      $data['count'] =  1;
      $data['show_str'] =  implode("+",$key_list);
      return $data;
  }
  
  /**
  * 获取一个项目的控制类型统计
  * 
  * @param mixed $id  项目ID
  */
  function getProjectControl($id){
      
      //取得所有的设备
      $where['project_id'] = $id;
      $list = M('project_device')
      ->alias("pd")
      ->join(C('DB_PREFIX').'cpn_class_group cg ON cg.cpn_type = pd.cpn_type and cg.group_code = pd.group_code')
      ->field("pd.*,cg.group_name,concat(pd.cpn_type,pd.group_code) as groups")
      ->where($where)->order('cpn_type,group_code')->select();
      $group = "";
      $show = array();
      foreach($list as $k =>$v){
          $param =  getDeviceControl($v['id']);
          $key = $v['groups']."_".$param['str'];
          $temp =array();
          $temp['group_name'] = $v['group_name'];
          $temp['count'] = $param['count'];
          $temp['show_str'] = $param['show_str']; 
          $show[$key][] = $temp;
          
      }
      $sum = array();
      foreach($show as $k =>$v){
          $temp =array();
          $temp['group_name'] =  $v[0]['group_name'];
          $temp['show_str'] = $v[0]['show_str'];
          $count = 0;
          foreach($v as $sub_k =>$sub_v){
                $count = $count + $sub_v['count'];
          }
          $temp['count'] = $count;
          $sum[]= $temp;
      }
      //dump($sum);
      return $sum;
      
      
      
      
  }
    
  /**
  * 获取一个设备的传感器参数类型统计
  * 
  * @param mixed $device_id
  */
  function getDeviceSensor($device_id){
      $param_list = getDeviceSensorParam($device_id);
      $sum_list = array();
      foreach($param_list as $k =>$v){
           $key = $v['sensor_type']."#".$v['key_str'] ;
           $sum_list[$key]['list'][] =1;
           $sum_list[$key]['name']  = $v['sensor_name'];
           $sum_list[$key]['param_str']  = $v['show_str'];
           $sum_list[$key]['count'] = count($sum_list[$key]['list']);

      }
      return $sum_list;
  }
  
   /**
  * 获取一个项目的传感器参数类型 统计
  * 
  * @param mixed $id   项目ID
  */
  function getProjectSensor($id){
      set_time_limit(0);
      //取得所有的设备
      $where['project_id'] = $id;
      $list = M('project_device')
      ->alias("pd")
      ->join(C('DB_PREFIX').'cpn_class_group cg ON cg.cpn_type = pd.cpn_type and cg.group_code = pd.group_code')
      ->field("pd.*,cg.group_name,concat(pd.cpn_type,pd.group_code) as groups")
      ->where($where)->order('cpn_type,cpn_type')->select();
      $group = "";
      $show = array();
      $sum_list = array();

      foreach($list as $p_k =>$p_v){
          $param_list = getDeviceSensorParam($p_v['id']);
          foreach($param_list as $k =>$v){
               $key = $v['sensor_type']."#".$v['key_str'] ;
               $sum_list[$key]['list'][] =1;
               $sum_list[$key]['name']  = $v['sensor_name'];
               $sum_list[$key]['sorts']  = intval($v['sorts']);
               $sum_list[$key]['param_str']  = $v['show_str'];
               $sum_list[$key]['count'] = count($sum_list[$key]['list']);
          }
          
      }
     // dump($sum_list);
      $sotrs = array_column($sum_list,'sorts');
      array_multisort($sotrs,SORT_ASC,$sum_list);
     // dump($sum_list);
      return  $sum_list;
      
      
      
      
  }

  
    //
   /**
   * 获取一个设备的传感器参数类型.
   * 
   * @param mixed $device_id
   */
  function getDeviceSensorParam($device_id){
      //
      $where['project_device_id'] = $device_id;
      $where['dc.is_count'] =1;
      //获取参数
      $param_list =  M('project_design')->alias("pd")
      ->join(C('DB_PREFIX').'device_class_param cp ON pd.param_id = cp.id')
      ->join(C('DB_PREFIX').'device_sensor dc ON dc.sensor_code = cp.sensor_type')
      ->where($where)
      ->group("cp.sensor_type,cp.sensor_type_group")
      ->field("dc.sensor_name,pd.*,cp.sensor_type,cp.sensor_type_group,dc.sorts,dc.is_count")
      ->order("dc.sorts,cp.sensor_type_group")
      ->select();

      
      //获取参数
      foreach($param_list as $k => &$v){
           //先判断是否设置
           $param_where = array();
           $param_where['p.device_id'] = $device_id;
           $param_where['p.sensor_code'] = $v['sensor_type'];
           $param_where['p.sensor_type_group'] = $v['sensor_type_group'];
           $param_detail_list = M('project_device_sensor_param')->alias('p')
            ->join(C('DB_PREFIX').'device_sensor_param sp ON p.sensor_param_id=sp.id')
            ->field('sp.id,sp.sensor_param_name,sp.sensor_param_unit,p.value')
            ->where($param_where)
            ->order('sp.id')
            ->select();
           if(!$param_detail_list )  {
                  //获取参数
                  $param_where = array();
                  $param_where['sensor_code'] = $v['sensor_type'];
                  $param_detail_list =  M('device_sensor_param')->alias("sp")
                  ->where($param_where)
                  ->field("sp.id,sp.sensor_param_name,sp.sensor_param_unit,sp.sensor_param_value as value")
                  ->order("sp.id")
                  ->select();
           }
           //开始组织参数
           $detail_list = array();
          // $arr2 = array_map('array_shift',$arr);
           $key_str ="";
           $show_str ="";
           foreach($param_detail_list as $sub_k =>$sub_v){
               $key_str = $key_str.$sub_v['id']."_".$sub_v['value']."#";
               $show_str = $show_str.$sub_v['sensor_param_name']."：".$sub_v['value'].' '.$sub_v['sensor_param_unit']."#";
           }
           $v['key_str'] = $key_str;
           $v['show_str'] = substr($show_str,0,strlen($show_str)-1);
           
      } 
      return $param_list;
      
     
  }
  function formatTime($timestamp) {
    if($timestamp === null) return "***";
    $remain_time = $timestamp;
    $day = floor($remain_time / (3600*24));
    $day = $day > 0 ? $day.'天' : '';
    $hour = floor(($remain_time % (3600*24)) / 3600);
    $hour = $hour > 0 ? $hour.'小时' : '';
    $minutes ="";
    if($day == "" && $hour == "" ){
       $minutes = floor((($remain_time % (3600*24)) % 3600) / 60);
       $minutes = $minutes.'分';
    }
    //$minutes = floor((($remain_time % (3600*24)) % 3600) / 60);
    //$minutes = $minutes > 0 ? $minutes.'分' : '';
    //$second  = $remain_time%60;
    //$second =  $second > 0 ? $second.'秒' : '';
    return $day.$hour.$minutes;
   // return $day.$hour.$minutes.$second;


}
function formatHour($timestamp) {
    $remain_time = $timestamp;
    $hour = floor($remain_time / 3600);
    $hour = $hour > 0 ? $hour  : '00';
    $minutes = floor(($remain_time % 3600)/ 60);
    $minutes = $minutes > 0 ? $minutes : '00';
    //$second  = $remain_time%60;
    //$second =  $second > 0 ? $second.'秒' : '';
    return str_pad($hour,2,'0',STR_PAD_LEFT).":".str_pad($minutes,2,'0',STR_PAD_LEFT);
   // return $day.$hour.$minutes.$second;


}
function formatNormal($value){
       if($value === null) return "***";
       $str = "";
       //return  $value;
       if($value == 0){
          $str = "正常";
       }
       else if($value == 1){
          $str = "<span style='color:red'>异常</span>";
       }
       return $str;

  }

  function formatDate($format,$value){
       $str = "";
       if($value != null && $value != 0){
           $str = date($format,$value);
       }

       return $str;

  }

  function formatStatus($value){
        $str = "通过";
       //return  $value;
       if($value == 1){
          $str = "等待审核";
       }else if($value == 0){
          $str = "审核不过";
       }
       return $str;

  }



 function writeLog($userid, $act_type, $act_content='',  $value='', $project_id='', $device_id=0, $cpn_name=''){
    // $act_type: 1-系统相关 2-项目相关
	$Log = M('log');
	$data['userid'] = $userid;
	$data['act_type'] = $act_type;
   $data['act_content'] = $act_content;
	$data['project_id'] = $project_id;
	$data['value'] = $value;
	$data['device_id'] = $device_id;
	$data['cpn_name'] = $cpn_name;
	$data['date'] = time();
	$data['ip'] = get_client_ip(0, true);
   $session_function_id = session('function_id');
   $mFunction_list = explode(",",$session_function_id);
   if (in_array("1001", $mFunction_list)) {
      $data['is_hidden'] = 1;
   }
	$Log->add($data);
  }

function addMessage($to_userid, $title='', $content='', $value=0, $type=1){
   $data['from_userid'] =session(C('SESSION_ADMIN_ID'));
   $data['to_userid'] = $to_userid;
   $data['title'] = $title;
   $data['content'] = $content;
   $data['value'] = $value;
   $data['type'] = $type;
   $data['datetime'] = date('Y-m-d H:i:s');
   $res = M('member_message')->add($data);
   return $res ? true : false;
}

 function http_post($url,$param,$post_file=false){
	$oCurl = curl_init();
	if(stripos($url,"https://")!==FALSE){
		curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
	}
	if (is_string($param) || $post_file) {
		$strPOST = $param;
	} else {
		$aPOST = array();
		foreach($param as $key=>$val){
			$aPOST[] = $key."=".urlencode($val);
		}
		$strPOST =  join("&", $aPOST);
	}
	curl_setopt($oCurl, CURLOPT_URL, $url);
	curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt($oCurl, CURLOPT_POST,true);
	curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
	$sContent = curl_exec($oCurl);
	$aStatus = curl_getinfo($oCurl);
	curl_close($oCurl);
	if(intval($aStatus["http_code"])==200){
		return $sContent;
	}else{
		return false;
	}
}

/**
 * 模拟HTTP GET
 */
function http_get($url){
	$oCurl = curl_init();
	if(stripos($url,"https://")!==FALSE){
		curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
	}
	curl_setopt($oCurl, CURLOPT_URL, $url);
	curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
	$sContent = curl_exec($oCurl);
	$aStatus = curl_getinfo($oCurl);
	curl_close($oCurl);
	if(intval($aStatus["http_code"])==200){
		return $sContent;
	}else{
		return false;
	}
}

/**
 * 获取文件扩展名
 */
function get_extension($file)
{
	return strtolower(pathinfo($file, PATHINFO_EXTENSION));
}

function encrypt($encryptKey, $str){
	$iv = '0102030405060708';
	return openssl_encrypt($str, 'AES-128-CBC',$encryptKey,0,$iv);
}


function decrypt($encryptKey, $str){
	$iv = '0102030405060708';
	return openssl_decrypt($str, 'AES-128-CBC', $encryptKey, 0, $iv);
}

function sendMail($to, $title, $content) {
 
	Vendor('PHPMailer.PHPMailerAutoload');     
	$mail = new \PHPMailer(); //实例化
	//$mail->SMTPDebug = 1;
	$mail->IsSMTP(); // 启用SMTP
	$mail->Host=C('MAIL_HOST'); //smtp服务器的名称（这里以QQ邮箱为例）
	//$mail->Port = 465;
	$mail->Port = 25;
	//$mail->SMTPSecure = "ssl";
	$mail->SMTPAuth = C('MAIL_SMTPAUTH'); //启用smtp认证
	$mail->Username = C('MAIL_USERNAME'); //你的邮箱名
	$mail->Password = C('MAIL_PASSWORD') ; //邮箱密码
	$mail->From = C('MAIL_FROM'); //发件人地址（也就是你的邮箱地址）
	$mail->FromName = C('MAIL_FROMNAME'); //发件人姓名
	if(is_array($to)){
		foreach($to as $addr){
			$mail->addBCC($addr);
		}
	} else {
		$mail->AddAddress($to,"尊敬的用户");
	}
	$mail->WordWrap = 50; //设置每行字符长度
	$mail->IsHTML(C('MAIL_ISHTML')); // 是否HTML格式邮件
	$mail->CharSet=C('MAIL_CHARSET'); //设置邮件编码
	$mail->Subject =$title; //邮件主题
	$mail->Body = $content; //邮件内容
	$mail->AltBody = "本邮件是HTML格式的，请在HTML模式下浏览"; //邮件正文不支持HTML的备用显示
	/*
	$mail->SMTPOptions = array(
		'ssl' => array(
			'verify_peer' => false,
			'verify_peer_name' => false,
			'allow_self_signed' => true
			)
		);
	*/
	return($mail->Send());
}

?>
